<template>
  <el-form :model="form" ref="form" :rules="rules" class="form">
    <el-form-item class="form-item" prop="username">
      <el-input placeholder="用户名/手机" v-model="form.username" @focus="hideMsg('username')"></el-input>
    </el-form-item>

    <el-form-item class="form-item" prop="password">
      <el-input
        placeholder="密码"
        type="password"
        v-model="form.password"
        @focus="hideMsg('password')"
      ></el-input>
    </el-form-item>

    <p class="form-text">
      <nuxt-link to="#">忘记密码</nuxt-link>
    </p>

    <el-button class="submit" type="primary" @click="handleLoginSubmit">登录</el-button>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      // 表单数据
      form: {
        username: "",
        password: ""
      },
      // 表单规则
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            pattern: /^\d{5,8}$/,
            message: "密码5-8位数字组成",
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    //聚焦时表单验证取消
    hideMsg(proName) {
      this.$refs.form.clearValidate(proName);
    },
    // 提交登录
    handleLoginSubmit() {
      //validate函数是Element表单的方法,有两个参数,第一个参数代表全部表单通过的布尔值,第二个参数代表没通过的字段
      this.$refs.form.validate((isValid, itemNotValid) => {
        console.log(isValid);
        console.log(itemNotValid);
        if (isValid) {
          //   console.log("验证成功,可以发送请求" + this.form);
          //   this.$axios({
          //     url: "/accounts/login",
          //     method: "POST",
          //     data: this.form
          //   }).then(res => {
          //     // console.log(res.data);
          //     this.$store.commit("user/setusername", res.data);
          //     console.log(this.$store.state.user.username);
          //   });
          this.$store.dispatch("user/login", this.form).then(res => {
            console.log("登录成功");
            console.log(res);
            this.$message.success("登录成功");
            if (this.$route.path == "/user/login") {
              setTimeout(() => {
                this.$router.push("/");
              }, 800);
            }
          });
        } else {
          console.log("验证失败，不能发送请求");
        }
      });
      //第二种方法
      //   this.$refs.form
      //     .validate()
      //     .then(res => {
      //       console.log(res);
      //     })
      //     .catch(err => {
      //       console.log(err);
      //     });
    }
  }
};
</script>

<style scoped lang="less">
.form {
  padding: 25px;
}

.form-item {
  margin-bottom: 20px;
}

.form-text {
  font-size: 12px;
  color: #409eff;
  text-align: right;
  line-height: 1;
}

.submit {
  width: 100%;
  margin-top: 10px;
}
</style>